package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.CdcAllergyMapper;
import com.dhcc.cdc.busi.dao.CdcEpisodeMapper;
import com.dhcc.cdc.busi.dao.CdcUserMapper;
import com.dhcc.cdc.busi.entity.CdcAllergyEntity;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.entity.CdcUserEntity;
import com.dhcc.cdc.busi.service.ICdcAllergyService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 过敏记录表数据服务层接口
 * 
 * @ClassName: CdcAllergyServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:09
 */
@Service("cdcAllergyService")
public class CdcAllergyServiceImpl extends BaseServiceImpl<CdcAllergyMapper, CdcAllergyEntity>
		implements ICdcAllergyService {

	@Autowired
	private CdcEpisodeMapper cdcEpisodeMapper;
	
	@Autowired
	private CdcDataMapper cdcDataMapper;
	
	@Autowired
	private CdcUserMapper cdcUserMapper;

	@Override
	public List<CdcAllergyEntity> page(Page<CdcAllergyEntity> page, Map<String, Object> map) {
		return this.baseMapper.page(page, map);
	}

	@Override
	public List<CdcAllergyEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	@Override
	public String handleXmlData(String dataStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			Iterator<Element> iter = rootElt.elementIterator("allergy"); // 获取根节点下的子节点allergy
			// 遍历allergy节点
			while (iter.hasNext()) {
				Element allergyEle = iter.next();
				String code = allergyEle.elementTextTrim("code"); // 过敏代码
				String episodeid = allergyEle.elementTextTrim("episodeid"); // 就诊记录
				String description = allergyEle.elementTextTrim("description"); // 描述
				String alledatestr = allergyEle.elementTextTrim("alledate"); // 记录日期
				String updatetimestr = allergyEle.elementTextTrim("updatetime"); //更新时间
                String updateuserid = allergyEle.elementTextTrim("updateuserid"); //更新人
				String opercode = allergyEle.elementTextTrim("opercode"); // 操作码
				CdcAllergyEntity allergy = new CdcAllergyEntity();
				allergy.setCode(code);
				CdcEpisodeEntity cdcEpisodeEntity = new CdcEpisodeEntity();
				cdcEpisodeEntity.setXcode(episodeid);
				cdcEpisodeEntity = cdcEpisodeMapper.selectOne(cdcEpisodeEntity);
				Long epsid = cdcEpisodeEntity.getId();
				allergy.setEpisodeId(epsid);
				//获取dataid
            	CdcDataEntity cdcDataEntity = new CdcDataEntity();
            	cdcDataEntity.setCode("AllergyData");
            	cdcDataEntity.setIsActive(1);
            	cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
        		Long dataId = cdcDataEntity.getId();
        		//获取basedataId
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
        		if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		allergy.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		allergy.setUpdateBy(updateuser);
            	}
				if ("1".equals(opercode)) {// 保存/修改
					if (CommonUtil.isNotEmpty(description)) {
						allergy.setDescription(description);
					}
					if (CommonUtil.isNotEmpty(alledatestr)) {
						Date alledate = sdf.parse(alledatestr);
						allergy.setAlleDate(alledate);
					}
            		allergy.setDataId(dataId);
					allergy.setIsActive(1);
				} else {
					allergy.setIsActive(0);
				}
				// 先判断是不是有该对象
				Wrapper<CdcAllergyEntity> wrapper = new EntityWrapper<CdcAllergyEntity>();
				wrapper.eq("episode_id", allergy.getEpisodeId());
				wrapper.eq("code", allergy.getCode());
				wrapper.eq("data_id", dataId);
				int count = this.selectCount(wrapper);
				if (count > 0) {
					this.update(allergy, wrapper);
				} else {
					this.insert(allergy);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		} catch (Exception e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		}
		return "<response><status>1</status><message>ok</message></response>";
	}

}